package cn.bb.bbstudy.controller;

import cn.bb.bbstudy.pojo.Blog;
import cn.bb.bbstudy.pojo.BlogCategory;
import cn.bb.bbstudy.pojo.Comment;
import cn.bb.bbstudy.pojo.User;
import cn.bb.bbstudy.service.*;
import cn.bb.bbstudy.utils.BBUtils;
import cn.bb.bbstudy.vo.BlogWriteForm;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
public class BlogController {

    @Autowired
    BlogService blogService;
    @Autowired
    BlogCategoryService blogCategoryService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;
    @Autowired
    FileUploadService fileUploadService;

    // 编辑一个新的博客 这是展示页
    @GetMapping("/blog/write")
    public String toWrite(Model model) {
        //查询所有博客的标签 放入
        List<BlogCategory> categoryList = blogCategoryService.selectAll();
        model.addAttribute("categoryList", categoryList);
        return "blog/write";
    }

    /**
     * 博客列表展示请求
     */
    @GetMapping("/blog")
    public String lists(Model model,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "10") int limit) {
        //默认一页显示10条数据 根据更新的时间来定
        PageHelper.startPage(page, limit);
        PageInfo<Blog> info = new PageInfo<>(blogService.findAllDesc());
        model.addAttribute("info", info);
        List<BlogCategory> categories = blogCategoryService.selectAll();
        model.addAttribute("categoryList", categories);
        return "blog/list";
    }

    @GetMapping("/blog/read/{bid}")
    public String read(Model model, @PathVariable("bid") String bid) {
        Blog blog = blogService.findOneByBid(bid);
        //每刷新一次 浏览量+1
        blog.setViews(blog.getViews() + 1);
        blogService.updateByPrimaryKeySelective(blog);
        model.addAttribute("blog", blog);
        //评论里的topic_id 对应的就是博客对象里的bid
        List<Comment> comments = commentService.selectAllByTopic(bid);
        model.addAttribute("comments", comments);
        return "blog/read";
    }

    /**
     * 保存博客
     *
     * @param blogWriteForm
     * @return
     */
    @PostMapping("/blog/write")
    public String save(BlogWriteForm blogWriteForm) {
        //接受博客表单vo
        Blog blog = new Blog();
        String bid = BBUtils.getUuid();
        blog.setBid(bid);
        blog.setTitle(blogWriteForm.getTitle());
        blog.setContent(blogWriteForm.getContent());
        blog.setSort(0);
        blog.setViews(0);
        //设置用户相关
        blog.setAuthorId(blogWriteForm.getAuthorId());
        blog.setAuthorAvatar(blogWriteForm.getAuthorAvatar());
        blog.setAuthorName(blogWriteForm.getAuthorName());
        //设置栏目相关
        BlogCategory category = blogCategoryService.selectByPrimaryKey(blogWriteForm.getCategoryId());
        blog.setCategoryId(category.getId());
        blog.setCategoryName(category.getCategory());
        blog.setGmtCreate(BBUtils.getTime());
        blog.setGmtUpdate(BBUtils.getTime());
        blogService.insertSelective(blog);

        return "redirect:/blog/read/" + bid;

    }

    /**
     * 更新博客
     * @param blog
     * @return
     */
    @PostMapping("/blog/edit")
    public String update(Blog blog) {
        BBUtils.print(blog);
        String bid = blog.getBid();
        Blog queryBlog = blogService.findOneByBid(bid);
        queryBlog.setTitle(blog.getTitle());
        queryBlog.setContent(blog.getContent());
        queryBlog.setCategoryId(blog.getCategoryId());
        queryBlog.setGmtUpdate(BBUtils.getTime());
        blogService.updateByPrimaryKeySelective(queryBlog);
        return "redirect:/blog/read/" + bid;
    }

    /**
     * 删除博客
     */
    @GetMapping("blog/delete/{uid}/{bid}")
    public String delete(@PathVariable("uid") String uid,@PathVariable("bid") String bid) {
        //删除两张表的数据 博客表  评论表对应的都要删掉 评论就别删了 太麻烦了
        Blog blog = blogService.findOneByBid(bid);
        User user = userService.findUserByUid(uid);
        BBUtils.print(user);
        if (blog.getAuthorId().equals(uid) || user.getRoleId() == 1) {
            blogService.deleteByPrimaryKey(blog.getId());
            BBUtils.print("删除成功");
            return "redirect:/blog";
        } else {
            return "error/404";
        }

    }
    /**
     * 编辑博客
     */
    @GetMapping("blog/edit/{uid}/{bid}")
    public String edit(Model model,@PathVariable("uid") String uid,@PathVariable("bid") String bid) {
        //根据bid 得到blog对象 进行回显 同时标签集合也要传到前端
        //只有该用户或者管理员可以进行修改
        User user = userService.findUserByUid(uid);
        Blog blog = blogService.findOneByBid(bid);
        BBUtils.print(user);
        if (blog.getAuthorId().equals(uid) || user.getRoleId() == 1) {
            model.addAttribute("blog", blog);
            //查询所有标签
            List<BlogCategory> categories = blogCategoryService.selectAll();
            model.addAttribute("categoryList", categories);
            return "blog/edit";
        } else {
            BBUtils.print("非法编辑");
            return "error/404";
        }
    }

    /**
     *  发表评论
     * @param bid
     * @param comment
     * @return
     */
    @PostMapping("/blog/comment/{bid}")
    public String comment(@PathVariable("bid") String bid, Comment comment) {
        BBUtils.print(comment);
        comment.setCommentId(BBUtils.getUuid());
        //1为博客 2为博客
        comment.setTopicCategory(2);
        comment.setGmtCreate(BBUtils.getTime());
        commentService.insertSelective(comment);
        Blog blog = blogService.findOneByBid(bid);
        //重定向到博客详情页
        return "redirect:/blog/read/" + bid;
    }


    /**
     * 编辑器图片上传
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/blog/write/file/upload")
    @ResponseBody
    //editormd-image-file不可更改
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String upload = fileUploadService.upload(file);
        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", upload);
        res.put("success", 1);
        res.put("message", "upload success!");
        BBUtils.print(res.toJSONString());
        return res;
    }
}
